package servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthorityFilter implements Filter {
	
	private FilterConfig config;

	@Override
	public void destroy() {
		this.config=null;
		System.out.println("-------filter-----destroy-------");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		System.out.println("-------filter-----doFilter-------");
		
		String encoding=config.getInitParameter("encoding");
		String loginPage=config.getInitParameter("login");
		
		request.setCharacterEncoding(encoding);
		
		HttpServletRequest hrequest=(HttpServletRequest)request;
		HttpServletResponse hresponse=(HttpServletResponse)response;
		
		HttpSession session=hrequest.getSession(true);
		String requestPath=hrequest.getServletPath();
		
		System.out.println("------authroty----path:"+requestPath);
		System.out.println("------authroty----session:"+session.getAttribute("user"));
		
		if(session.getAttribute("user")==null&&!requestPath.endsWith(loginPage)&&
				!requestPath.endsWith("/LoginServlet")){
			System.out.println("------authroty----stop");
			request.setAttribute("tip","您还没有登录");
			request.getRequestDispatcher(loginPage).forward(request, response);
		}else{
			System.out.println("------authroty----pass");
			filterChain.doFilter(request, response);
		}
		
		
		
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.config=config;
		System.out.println("-------filter-----init-------");
	}

}
